package com.xuebank.nfe.nfecar.fragment


import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.provider.ContactsContract
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import android.widget.LinearLayout
import com.trello.rxlifecycle.android.ActivityEvent
import com.wzn.libaray.event.RxBus
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.MainActivity

import com.xuebank.nfe.nfecar.R
import com.xuebank.nfe.nfecar.activity.SecondActivity
import com.xuebank.nfe.nfecar.beas.BaseFragment
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.model.RefreshHtml
import com.xuebank.nfe.nfecar.utils.CacheUtils
import com.xuebank.nfe.nfecar.utils.NfeConstants
import com.xuebank.nfe.nfecar.utils.XueBankUtils
import com.xuebank.nfe.nfecar.utils.bridge.BridgeWebView
import com.xuebank.nfe.nfecar.utils.bridge.BridgeWebViewClient
import com.xuebank.nfe.nfecar.utils.statusbar.StatusBarUtil
import org.json.JSONObject


/**
 * A simple [Fragment] subclass.
 */
class NewsFragment : BaseFragment() {

    private var webSettings: WebSettings? = null
    private val APP_CACAHE_DIRNAME = "/webcache"
    private var newWebView: BridgeWebView? = null
    private val mList = java.util.ArrayList<String>()
    internal var mWebView: BridgeWebView? = null
    internal var llWebView: LinearLayout? = null
    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun initViews() {
        initWebView()
        RxBus.getDefault().toObserverable(RefreshHtml::class.java)
                .compose(this.bindUntilEvent(com.trello.rxlifecycle.android.FragmentEvent.DESTROY))
                .subscribe({ reques ->
                    try {
                        val refreshHtml = RefreshHtml()
                        val isRefresh =refreshHtml.refresh
                        val jsonObject = JSONObject()
                        val flag = if (isRefresh == true) "1" else "0"
                        jsonObject.put("isRefresh", flag)
                        //                    webViewSendRequest("");
                        val json = JSONObject()
                        json.put("action", "StartRefresh")
                        json.put("data", jsonObject)
                        mWebView?.callHandler("XueBankWebViewNativeBridge", json.toString(), null)
                        mWebView?.loadUrl(Constants.NEWS_URL)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                })
    }

    override fun findViews() {
        mWebView = findViewById(R.id.news_web_view)
        llWebView = findViewById(R.id.new_ll_webfragemnt)

    }
    override fun onResume() {
        super.onResume()
        StatusBarUtil.setColor(activity, ContextCompat.getColor(activity!!, R.color.white))
        StatusBarUtil.setTranslucent(activity)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        //不为空则结束
        if (mWebView != null) {
            mWebView?.destroy()
        }
        StatusBarUtil.setColor(activity, ContextCompat.getColor(activity!!, R.color.white))
        StatusBarUtil.setTranslucent(activity)
        return inflater.inflate(R.layout.fragment_news, container, false)
    }




    private fun initWebView() {
        webSettings = mWebView?.settings
        webSettings?.javaScriptEnabled = true
        val userAgentString = webSettings?.userAgentString
        webSettings?.userAgentString = userAgentString + ";ICBCAndroidBSXB"
        webSettings?.allowFileAccess = true
        webSettings?.setSupportZoom(false)
        webSettings?.allowContentAccess = true
        webSettings?.useWideViewPort = true
        webSettings?.loadWithOverviewMode = true
        webSettings?.loadsImagesAutomatically = true
        //        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        val defaultUserAgent = webSettings?.getUserAgentString()
        //webSettings.setUserAgentString(Constants.WebViewUA + " " + ICBCUtil.getVerName() + " fullversion:" + ICBCUtil.getFullVerCode() + " " + defaultUserAgent);
        if (Build.VERSION.SDK_INT >= 11)
            mWebView?.settings?.allowContentAccess = true
        if (Build.VERSION.SDK_INT >= 21)
            mWebView?.settings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        setWebViewCacheMode()
    }


    private fun setWebViewCacheMode() {
        webSettings?.setRenderPriority(WebSettings.RenderPriority.HIGH)
        webSettings?.javaScriptCanOpenWindowsAutomatically = true
        // 支持多窗口
        webSettings?.setSupportMultipleWindows(true)
        // 开启 DOM storage API 功能
        webSettings?.domStorageEnabled = true
        // 开启 Application Caches 功能
        webSettings?.setAppCacheEnabled(true)
        val cacheDirPath = context.filesDir.absolutePath + APP_CACAHE_DIRNAME
        //设置数据库缓存路径
        webSettings?.setDatabasePath(cacheDirPath)
        //设置  Application Caches 缓存目录
        webSettings?.setAppCachePath(cacheDirPath)
        webSettings?.setDatabaseEnabled(true)
        //通过xml资源文件获得animation实例
        //        iv_background.setImageResource(R.drawable.anim_xb);
        //        xbAnimation = (AnimationDrawable) iv_background.getDrawable();
        mWebView?.webChromeClient = object : WebChromeClient() {

            override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean {
                newWebView = BridgeWebView(context)
                newWebView?.webViewClient = object : WebViewClient() {
                    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                        val intent = Intent(activity, SecondActivity::class.java)
                        intent.putExtra("url", url)
                        startActivityForResult(intent, NfeConstants.REFRESH_REQUEST)
                        return true
                    }
                }
                //                initWebView(newWebView);//初始化webview
                llWebView?.addView(newWebView)
                val transport = resultMsg.obj as WebView.WebViewTransport//以下的操作应该就是让新的webview去加载对应的url等操作。
                transport.webView = newWebView
                resultMsg.sendToTarget()
                return true
            }

            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                result?.confirm()
                return true
            }

            override fun onExceededDatabaseQuota(url: String, databaseIdentifier: String, quota: Long, estimatedDatabaseSize: Long, totalQuota: Long, quotaUpdater: WebStorage.QuotaUpdater) {
                //设置数据库存储大小
                quotaUpdater.updateQuota(estimatedDatabaseSize * 2)
            }
            /*** 视频播放相关的方法  */

        }
        mWebView?.webViewClient = object : BridgeWebViewClient(mWebView) {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.i(TAG, url)
                //                start();
            }

            @RequiresApi(Build.VERSION_CODES.M)
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.e(TAG, "onPageFinished")
                requestData()
                //                stop();
                //                homeHeadView.setVisibility(View.GONE);
                mWebView?.setOnLongClickListener(View.OnLongClickListener { true })


            }

            override fun onLoadResource(view: WebView?, url: String?) {
                Log.i(TAG, url)
                super.onLoadResource(view, url)
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.i(TAG, url)
                return super.shouldOverrideUrlLoading(view, url)
            }

            override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
            }
        }
        mWebView?.setOnTouchListener(View.OnTouchListener { v, event ->
            mWebView?.getParent()?.requestDisallowInterceptTouchEvent(true)
            val x = event.rawX.toInt()
            val y = event.rawY.toInt()
            var lastX = 0
            var lastY = 0
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastX = x
                    lastY = y
                }
                MotionEvent.ACTION_MOVE -> {
                    val deltaY = y - lastY
                    val deltaX = x - lastX
                    if (Math.abs(deltaX) < Math.abs(deltaY)) {
                        mWebView?.getParent()?.requestDisallowInterceptTouchEvent(true)
                    } else {
                        mWebView?.getParent()?.requestDisallowInterceptTouchEvent(true)
                    }
                }
                else -> {
                }
            }
            false
        })
//        if (SharedPreferencesUtil.getInstance(context).getString(MainActivity.COOKIE) != null) {
////            MainActivity.synCookies(Constants.MINE_URL, context)
//            MainActivity.synchronousWebCookies(context,Constants.MINE_URL)
//
//            mWebView?.loadUrl(Constants.MINE_URL)
//        } else {
            mWebView?.loadUrl(Constants.NEWS_URL)
//        }
    }


    @RequiresApi(Build.VERSION_CODES.M)
    private fun requestData() {
        mWebView?.registerHandler("XueBankWebViewJavascriptBridge") { data, function ->
            Log.e("BridgeHandler", data)
            var jsonObject: JSONObject? = null
            try {
                val xbutils = XueBankUtils(activity)
                jsonObject = JSONObject(data)
                val send_action = jsonObject.getString("action")
                xbutils.doBridgeHandler(data) { result ->
                    Log.e("onCallBack", result)
                    function.onCallBack(result)
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == NfeConstants.REFRESH_OK) {
            if (requestCode == NfeConstants.REFRESH_REQUEST) {
                try {
                    val isRefresh = CacheUtils.getBoolean("isRefresh")
                    val jsonObject = JSONObject()
                    val flag = if (isRefresh == true) "1" else "0"
                    jsonObject.put("isRefresh", flag)
                    //                    webViewSendRequest("");
                    val json = JSONObject()
                    json.put("action", "StartRefresh")
                    json.put("data", jsonObject)
                    mWebView?.callHandler("XueBankWebViewNativeBridge", json.toString(), null)
                    mWebView?.loadUrl(Constants.NEWS_URL)
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            } else if (requestCode == NfeConstants.REFRESH) {
                val isReload = CacheUtils.getBoolean("isReload")
                if (isReload) {
                    mWebView?.reload()
                }
            } else {
                if (requestCode == NfeConstants.PICK_CONTACT) {
                    val contactUri = data?.data
                    val resolver = context.contentResolver
                    val c = resolver.query(contactUri!!, null, null, null, null)
                    if (c!!.moveToFirst()) {
                        val name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
                        var hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))
                        val contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID))
                        var phoneNumber: String? = null
                        if (hasPhone.equals("1", ignoreCase = true)) {
                            hasPhone = "true"
                        } else {
                            hasPhone = "false"
                        }
                        if (java.lang.Boolean.parseBoolean(hasPhone)) {
                            val phones = context.contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                                            + contactId, null, null)
                            while (phones.moveToNext()) {
                                phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                                mList.add(phoneNumber)
                            }
                            phones.close()
                        }
                        try {
                            val json = JSONObject()
                            json.put("personName", name)
                            json.put("personTels", mList.toString())

                            val jsonObject1 = JSONObject()
                            jsonObject1.put("action", "ReturnAddressBook")
                            jsonObject1.put("data", json)
                            mWebView?.callHandler("XueBankWebViewNativeBridge", jsonObject1.toString(), null)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                    }
                }
            }
        }
    }

}// Required empty public constructor
